package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestVo;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private HotelMapper hotelMapper;
    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestVo vo) {
        try {
            //1.创建请求对象,封装请求参数
            SearchRequest request = new SearchRequest("hotel");
            SearchSourceBuilder source = request.source();

            //1.1 构建查询条件
            buildBasicQuery(source, vo);

            //1.2 设置分页
            int pageNum = vo.getPage();
            int pageSize = vo.getSize();
            source.from((pageNum - 1) * pageSize);
            source.size(pageSize);

            //1.3 判断location是否有值,按照距离排序
            String location = vo.getLocation();
            if (StringUtils.isNotBlank(location)) {
                source.sort(SortBuilders
                        .geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS)
                );
            }

            //1.4 添加排序
            String sortBy = vo.getSortBy();
            if ("score".equals(sortBy)) {
                //如果按照score字段排序, 降序
                source.sort("score", SortOrder.DESC);
            }
            if ("price".equals(sortBy)) {
                //如果按照price字段排序 升序
                source.sort("price", SortOrder.ASC);
            }

            if (StringUtils.isNotBlank(vo.getKey())) {
                //1.5 添加高亮查询
                HighlightBuilder highlightBuilder = new HighlightBuilder();
                //设置高亮字段
                highlightBuilder.field("name");
                //设置前置标签
                highlightBuilder.preTags("<em>");
                //设置后置标签
                highlightBuilder.postTags("</em>");
                //不开启所搜条件字段检查
                highlightBuilder.requireFieldMatch(false);
                source.highlighter(highlightBuilder);
            }


            //2.发送请求,获取响应结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //3.解析响应结果
            PageResult result = handleResponse(response, vo);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> getFilters(RequestVo vo) {
        try {
            //1.创建请求对象,封装请求参数
            SearchRequest request = new SearchRequest("hotel");
            SearchSourceBuilder source = request.source();
            //1.1 设置查询条件
            buildBasicQuery(source, vo);

            //1.2 设置聚合条件
            source.size(0);
            buildAggregation(source);

            //2.发送请求,获取响应结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //3.解析响应结果
            Aggregations aggregations = response.getAggregations();
            Map<String, List<String>> map = new HashMap<>();
            List<String> brands = getAggByName(aggregations, "brandAgg");
            map.put("brand", brands);
            List<String> citys = getAggByName(aggregations, "cityAgg");
            map.put("city", citys);
            List<String> starName = getAggByName(aggregations, "starAgg");
            map.put("starName", starName);
            return map;

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 3.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 3.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 3.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 3.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

    /**
     * 构建聚合条件
     *
     * @param source
     */
    private void buildAggregation(SearchSourceBuilder source) {
        source.aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
        source.aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city")
                .size(100)
        );

        source.aggregation(AggregationBuilders
                .terms("starAgg")
                .field("starName")
                .size(100)
        );
    }

    private void buildBasicQuery(SearchSourceBuilder source, RequestVo vo) {
        //构建布尔查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1判断请求key是否为空,如果为空,查询所有,如果非空,全文搜索
        String key = vo.getKey();
        if (StringUtils.isBlank(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }

        //如果品牌brand不为空, term查询
        if (StringUtils.isNotBlank(vo.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", vo.getBrand()));
        }
        //如果星级startName不为空,用term查询
        if (StringUtils.isNotBlank(vo.getStartName())) {
            boolQuery.filter(QueryBuilders.termQuery("startName", vo.getStartName()));
        }

        //如果价格price不为空,使用range查询
        Integer minPrice = vo.getMinPrice();
        Integer maxPrice = vo.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lt(maxPrice));
        }
        //如果城市city不为空,使用term查询
        if (StringUtils.isNotBlank(vo.getCity())) {
            boolQuery.filter(QueryBuilders.termQuery("city", vo.getCity()));
        }

        //添加算分函数条件
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                //原始的查询条件
                boolQuery,
                // 算分函数 数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //算分函数
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),//筛选条件
                                ScoreFunctionBuilders.weightFactorFunction(10) //计算得分的方法
                        )
                }
        ).boostMode(CombineFunction.MULTIPLY); //加权模式:(算分和原始得分 进行计算) 默认相乘

        source.query(functionScoreQueryBuilder);

    }

    /**
     * 解析响应结果
     *
     * @param response 响应结果对象
     * @param vo
     * @return 查询分页对象
     */
    private PageResult handleResponse(SearchResponse response, RequestVo vo) {
        //解析响应数据
        SearchHits searchHits = response.getHits();
        //获取总文档条数
        long total = searchHits.getTotalHits().value;

        //创建hotelDocs对象用来存储数据
        List<HotelDoc> hotelDocs = new ArrayList<>();

        //获取文档soure
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            //获取文档的Json字符串
            String json = hit.getSourceAsString();
            // 将json字符串封装成hotelDoc对象 存入集合中
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //如果有排序字段 ,获取排序字段中的距离值
            if (StringUtils.isNotBlank(vo.getLocation())) {
                Object[] sortValues = hit.getSortValues();
                if (sortValues != null && sortValues.length > 0) {
                    hotelDoc.setDistance(sortValues[0]);
                }
            }

            //获取高亮处理结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                //获取高亮处理结果
                HighlightField highlightField = highlightFields.get("name");
                //高亮片段拼接字符串
                String highlightName = StringUtils.join(highlightField.getFragments());


                hotelDoc.setName(highlightName);
            }
            hotelDocs.add(hotelDoc);
        }

        //封装响应结果数据
        return new PageResult(total, hotelDocs);
    }
}

